package cn.zhibang.yygh.hosp.service.impl;

import cn.zhibang.yygh.DictFeignClient;
import cn.zhibang.yygh.enums.DictEnum;
import cn.zhibang.yygh.hosp.repository.HospitalRepository;
import cn.zhibang.yygh.hosp.service.DepartmentService;
import cn.zhibang.yygh.hosp.service.HospitalService;
import cn.zhibang.yygh.model.hosp.Hospital;
import cn.zhibang.yygh.vo.hosp.HospitalQueryVo;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service("HospitalService")
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    private HospitalRepository hospitalRepository;
    @Resource
    private DictFeignClient dictFeignClient;
    @Autowired
    private DepartmentService departmentService;
    @Override
    public void save(Map<String, Object> paramMap) {
//把参数map集合转换对象 Hospital医院对象
        //log.info(JSONObject.toJSONString(paramMap));
        String mapString = JSONObject.toJSONString(paramMap);
        Hospital hospital = JSONObject.parseObject(mapString, Hospital.class);

        //1.判断是否存在数据(根据编号查询)
        String hoscode = hospital.getHoscode();
        Hospital targetHospital = hospitalRepository.getHospitalByHoscode(hoscode);
        //在HospitalRepository中创建getHospitalByHoscode()方法（见下）
        System.err.println(targetHospital);
        //2.如果存在，进行修改
        if(null != targetHospital) {
            hospital.setId(targetHospital.getId());
            hospital.setStatus(targetHospital.getStatus());
            hospital.setCreateTime(targetHospital.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        } else { //3.如果不存在，进行添加
            hospital.setStatus(0); //0：未上线    1：已上线
            hospital.setCreateTime(new Date()); //获系统时间
            hospital.setUpdateTime(new Date()); //获系统时间
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }
    }

    @Override
    public Hospital getByHoscode(String hoscode) {
        return hospitalRepository.getHospitalByHoscode(hoscode);
    }

    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //0为第一页
        Pageable pageable = PageRequest.of(page-1, limit, sort);
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        //创建实例
        Example<Hospital> example = Example.of(hospital, matcher);
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);
// List<Hospital> content = pages.getContent(); //获得查询出来的数据
//获取查询list集合，遍历进行医院等级封装
        pages.getContent().stream().forEach(item -> {
            this.packHospital(item);
        });
        return pages;
    }
    private Hospital packHospital(Hospital hospital){
        String hostypeString  = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(), hospital.getHostype());
        String dictFeignClientName1 = dictFeignClient.getName(hospital.getProvinceCode());
        String dictFeignClientName2 = dictFeignClient.getName(hospital.getCityCode());
        String dictFeignClientName3 = dictFeignClient.getName(hospital.getDistrictCode());
        hospital.getParam().put("hostypeString",hostypeString);
        hospital.getParam().put("fullAddress", dictFeignClientName1+
                dictFeignClientName2+dictFeignClientName3+hospital.getAddress());
        return hospital;
    }
    @Override
    public void updateStatus(String id, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1) {
            Hospital hospital = hospitalRepository.findById(id).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }
    }
    @Override
    public Map<String, Object> show(String id) {
        Map<String, Object> result = new HashMap<>();
        Hospital hospital = this.packHospital(hospitalRepository.findById(id).get());
        result.put("hospital", hospital);
        //单独处理更直观
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }
    @Override
    public String getName(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        if(null != hospital) {
            return hospital.getHosname();
        }
        return "";
    }
    @Override
    public List<Hospital> findByHosname(String hosname) {
        //调用repository包中的方法，访问MongoDB中的医院数据
        return hospitalRepository.findHospitalByHosnameLike(hosname);
    }

    @Override
    public Map<String, Object> item(String hoscode) {
        Map<String,Object> result = new HashMap<>();
        Hospital hospital = this.packHospital(this.getByHoscode(hoscode));
        result.put("hospital", hospital);
        //预约规则
        result.put("bookingRule", hospital.getBookingRule());
        hospital.setBookingRule(null);
        return result;
    }

}
